/*
 * @Author: Mr.Mao
 * @Date: 2021-05-14 00:40:50
 * @LastEditTime: 2021-06-23 23:40:04
 * @Description: 
 * @LastEditors: Zhilong
 * @autograph: 任何一个傻子都能写出让电脑能懂的代码，而只有好的程序员可以写出让人能看懂的代码
 */
import { UserModel } from '../db'
import KoaRouter from 'koa-router'
import md5 from 'md5'
import { TOKEN_SECRET } from '../config'
import jwt from 'jsonwebtoken'
const user = new KoaRouter()

/**
 * @name 账号密码注册
 * @description 密码注册
 * @param account string 账号
 * @param password string 密码
 */
user.post('/accountRegister', async (ctx) => {
  const { account, password } = ctx.request.body
  if (!account || !password) ctx.throw(422, '账号密码必传')
  const searchResult = await UserModel.findOne({ account })
  if (searchResult) ctx.throw(400, '账号已存在')
  const userInfoDoc = await UserModel.create({
    account,
    password: md5(password)
  })
  if (!userInfoDoc) return ctx.throw(403, '创建失败');
  delete userInfoDoc.password;
  ctx.body = {
    token: jwt.sign({ _id: userInfoDoc._id }, TOKEN_SECRET, { expiresIn: '40h' }),
    ...userInfoDoc.toObject()
  }
})

/**
 * @name 账号密码登录
 * @param account string 账号
 * @param password string 密码
 */
user.post('/accountLogin', async (ctx) => {
  const { account, password } = ctx.request.body
  if (!account || !password) ctx.throw(422, '账号密码必传')
  const userInfoDoc = await UserModel.findOne({ account, password: md5(password) }, { password: false })
  if (!userInfoDoc) return ctx.throw(400, '用户名或密码错误')
  userInfoDoc.lastLoginTime = Date.now()
  await userInfoDoc.save()
  ctx.body = {
    token: jwt.sign({ _id: userInfoDoc._id }, TOKEN_SECRET, { expiresIn: '40h' }),
    ...userInfoDoc.toObject()
  }
})

/**
 * @name 修改用户信息
 */
user.post('/editUserInfo', async (ctx) => {
  const { _id } = ctx.state.user
  ctx.verifyParams(ctx.request.body, {
    nickName: {
      type: String,
      regExp: /^.{2,15}$/
    },
    gender: {
      type: String,
      regExp: /^women|men|secrecy$/
    },
    account: { intercept: false },
    password: { intercept: false },
  })

  await UserModel.updateOne({ _id }, ctx.request.body)
  const userInfo = await UserModel.findOne({ _id })
  ctx.body = userInfo && userInfo.toObject()
})
export default user